package src;

import javax.swing.*;
import java.awt.*;
import java.awt.Window;
import java.sql.*;

public class CustomerAddDialog extends AddDialog {
    public CustomerAddDialog(Window parent, Connection connection) {
        super(parent, "添加客户信息", connection);
        
        // 自动生成客户ID
        String nextCustomerId = generateNextCustomerId();
        JTextField customerIdField = new JTextField(nextCustomerId);
        customerIdField.setEditable(false); // 设置为不可编辑
        addInputField("ID:", customerIdField);
        
        addInputField("姓名:", new JTextField());
        addInputField("地址:", new JTextField());
        addInputField("电话:", new JTextField());
        
        // 添加业务员下拉框
        JComboBox<String> salesmanCombo = new JComboBox<>();
        salesmanCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT salesman_id, name FROM salesman");
            while (rs.next()) {
                String salesmanId = rs.getString("salesman_id");
                String salesmanName = rs.getString("name");
                salesmanCombo.addItem(salesmanName + " (" + salesmanId + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载业务员信息失败: " + e.getMessage());
        }
        addComboBox("业务员:", salesmanCombo);
        
        // 添加用水类型下拉框
        JComboBox<String> waterTypeCombo = new JComboBox<>();
        waterTypeCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT type_name FROM water_type");
            while (rs.next()) {
                waterTypeCombo.addItem(rs.getString("type_name"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用水类型失败: " + e.getMessage());
        }
        addComboBox("用水类型:", waterTypeCombo);

        confirmButton.addActionListener(e -> {
            try {
                String waterTypeId = getWaterTypeId(waterTypeCombo.getSelectedItem().toString());
                if (waterTypeId == null) {
                    JOptionPane.showMessageDialog(this, "无效的用水类型！");
                    return;
                }

                // 从业务员选择框中提取业务员ID
                String selectedSalesman = salesmanCombo.getSelectedItem().toString();
                String salesmanId = selectedSalesman.substring(selectedSalesman.lastIndexOf("(") + 1, selectedSalesman.lastIndexOf(")"));

                String sql = "INSERT INTO customer (customer_id, name, address, phone, salesman_id, water_type_id) VALUES (?, ?, ?, ?, ?, ?)";
                PreparedStatement pstmt = connection.prepareStatement(sql);
                pstmt.setString(1, customerIdField.getText());
                pstmt.setString(2, textFields.get("姓名:").getText());
                pstmt.setString(3, textFields.get("地址:").getText());
                pstmt.setString(4, textFields.get("电话:").getText());
                pstmt.setString(5, salesmanId);
                pstmt.setString(6, waterTypeId);
                
                pstmt.executeUpdate();
                JOptionPane.showMessageDialog(this, "客户添加成功！");
                dispose();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "添加客户失败: " + ex.getMessage());
            }
        });
    }

    private String generateNextCustomerId() {
        try {
            // 查询所有客户ID
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id FROM customer ORDER BY customer_id");
            
            // 如果没有客户记录，返回第一个ID
            if (!rs.next()) {
                return "CUST001";
            }
            
            // 创建一个集合来存储所有已使用的ID
            java.util.Set<Integer> usedIds = new java.util.HashSet<>();
            do {
                String currentId = rs.getString("customer_id");
                // 处理旧格式的ID（CUST开头）和新格式的ID（C开头）
                int num;
                if (currentId.startsWith("CUST")) {
                    num = Integer.parseInt(currentId.substring(4));
                } else {
                    num = Integer.parseInt(currentId.substring(1));
                }
                usedIds.add(num);
            } while (rs.next());
            
            // 从1开始查找第一个未使用的ID
            int nextNum = 1;
            while (usedIds.contains(nextNum)) {
                nextNum++;
            }
            
            // 生成新的ID，使用CUST前缀
            return String.format("CUST%03d", nextNum);
            
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "生成客户ID失败: " + e.getMessage());
            return "CUST001"; // 发生错误时返回默认ID
        }
    }

    private String getWaterTypeId(String typeName) throws SQLException {
        String sql = "SELECT water_type_id FROM water_type WHERE type_name = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, typeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getString("water_type_id");
        }
        return null;
    }
} 